﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XTYAPI.通讯
{
    public class Mitsubishi
    {
        public Mitsubishi()
        {
           
        }
        public string GetAddress(string str)
        {
            str = str.ToUpper();
            byte[] bs = Encoding.ASCII.GetBytes(str);
            for (int i = 0; i < bs.Length; i++)
            {
                if (bs[i]>=0x30&&bs[i]<=0x39)
                {
                    string typeData = str.Substring(0,i);//获取寄存器
                    string s = str.Replace(typeData, "");//获取地址
                    string a = s.ToString().PadLeft(5 - typeData.Length, '0');//补全
                    a = a.Insert(0, typeData);
                    return a;
                }
            }        
            return string.Empty;
        }
        public int MaxDelayCycle { get; set; } = 10;
        object lockModbus = new object();
        public SerialPort SerialPort { get; private set; }
        public string ErrorMsg { get; set; }
        public string[] GetPortNames()
        {
            return SerialPort.GetPortNames();
        }
        public bool Open(string portName, int baudRate = 9600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
        {
            try
            {
                SerialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
                return true;
            }
            catch (Exception ex)
            {
                ErrorMsg = ex.ToString();
                return false;
            }
        }
        public bool Close()
        {
            try
            {
                SerialPort?.Close();
                return true;
            }
            catch (Exception ex)
            {
                ErrorMsg = ex.ToString();
                return false;
            }
        }
        public string ReadBit(string address,int count)
        {
            // enq05h  站号 pc号 BR 报文等待*10ms 字符A区 和校验
            
            StringBuilder sb = new StringBuilder();
            sb.Append( "0");
            sb.Append("05");
            sb.Append("FF");
            sb.Append("BR");
            sb.Append("A");
            sb.Append(GetAddress(address));
            if (count<=255)
            {
                sb.Append("0");
            }
            sb.Append(count.ToString());
          
           byte[] recive= SendRecive(CalLrc(sb.ToString()))  ;
           string str = Encoding.ASCII.GetString(recive);

            return string.Empty;
        }
        public byte[] CalLrc(string str)
        {
            byte[] bs = Encoding.ASCII.GetBytes(str);
            bs[0] = 5;//查询
            short lrc = 0;
            for (int i = 1; i < bs.Length; i++)
            {
                lrc += bs[i];
            }
            lrc = (short)(lrc & 0xff);
            List<byte> ls = bs.ToList();
            byte lrcH = (byte)((lrc & 0xf0) >> 4);
            byte lrcL = (byte)(lrc & 0xf);
            byte[] bs1 = Encoding.ASCII.GetBytes(lrcL.ToString() + lrcH.ToString());
            ls.Add(bs1[1]);
            ls.Add(bs1[0]);
            return ls.ToArray();
        }
        public byte[] SendRecive(byte[] arry)
        {
            int delay = 0;
            try
            {
                Monitor.Enter(lockModbus);
                SerialPort?.Write(arry, 0, arry.Length);
                while (SerialPort.BytesToRead == 0)
                {
                    Thread.Sleep(100);
                    delay++;
                    if (delay > MaxDelayCycle)
                    {
                        break;
                    }
                }
                byte[] ResByte = new byte[SerialPort.BytesToRead];
                SerialPort.Read(ResByte, 0, ResByte.Length);
                return ResByte;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                Monitor.Exit(lockModbus);
            }
        }
        //public string ReadWord()
        //{

        //}
        //public string WriteBit()
        //{

        //}
        //public string WriteWord()
        //{

        //}
        //public string RunStopCpu(bool cpu)
        //{

        //}
    }
}
